package com.camel.chart.utils;

import com.camel.chart.utils.entity.Msg;
import org.apache.commons.io.input.ReversedLinesFileReader;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

public class SerializeUtil {
    public static void serializeObject(Object obj, String filename) {
        try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(Paths.get(filename)))) {
            out.writeObject(obj);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Object deserializeObject(String filename) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(filename)))) {
            return ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("文件读取异常");
            return null;
        }
    }

    public static String serializeObject(Object object) throws IOException {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        ObjectOutputStream stream = new ObjectOutputStream(byteStream);
        stream.writeObject(object);
        stream.close();
        return Base64.getEncoder().encodeToString(byteStream.toByteArray());
    }

    public static <T> T deserializeStringToObject(String serializedString) throws IOException, ClassNotFoundException {
        byte[] decode = Base64.getDecoder().decode(serializedString);
        ObjectInputStream stream = new ObjectInputStream(new ByteArrayInputStream(decode));
        T res = (T) stream.readObject();
        stream.close();
        return res;
    }

    public static void serializeObjAppendToFile(String fileName, String folderName, Object obj) {
        File folder = new File(folderName + "/");
        if(!folder.exists()) {
            folder.mkdir();
        }

        File file = new File(folderName + "/" + fileName);
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file.getPath(), true))) {
            writer.write(SerializeUtil.serializeObject(obj));
            writer.newLine(); // 写入一个新行
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static <T> Vector<T> deserializeFileToObjs(String fileName, String folderName, int startNum, int limitNum) {
        Vector<T> res = new Vector<>();
        File file = new File(folderName + "/" + fileName);
        if(!file.exists()) {
            return res;
        }
        String path = file.getPath();
        try (BufferedReader reader = Files.newBufferedReader(Paths.get(path))) {
            // 获取文件的行数
            int lines = (int) Files.lines(Paths.get(path)).count();
            // 计算起始行的位置
            int startLine = Math.max(0, lines - startNum - limitNum);
            if(startNum - limitNum > lines) {
                return res;
            }
            if(lines - startNum < 0) {
                return res;
            }
            limitNum = Math.min(limitNum, lines - startNum);
            // 反向读取指定行数的数据
            String[] linesRead = Files.lines(Paths.get(path))
                    .skip(startLine)
                    .limit(limitNum)
                    .toArray(String[]::new);

            // 打印读取的行
            for (String line : linesRead) {
                T o = deserializeStringToObject(line);
                res.add(o);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
//        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
//            String currentLine;
//            int currentLineNumber = 0;
//
//            while ((currentLine = reader.readLine()) != null) {
//                currentLineNumber++;
//                if (currentLineNumber >= startNum && currentLineNumber <=  (startNum + limitNum)) {
//                    T o = deserializeStringToObject(currentLine);
//                    res.add(o);
//                }
//            }
//        } catch (FileNotFoundException e) {
//            throw new RuntimeException(e);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        } catch (ClassNotFoundException e) {
//            throw new RuntimeException(e);
//        }
        return res;
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {

//        // 创建一个示例对象
//        MyObject myObject = new MyObject(1, "example");
//
//        // 序列化对象到文件
//        serializeObject(myObject, "myObject.ser");
//
//        // 反序列化对象从文件
//        MyObject deserializedObject = (MyObject) deserializeObject("myObject.ser");
//        System.out.println(deserializedObject.getId() + " " + deserializedObject.getName());
    }
}
